#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Data  :     2020/6/5 下午8:51
--------------------------------------
"""
import json
from datetime import datetime
from django.core.serializers import serialize
from django.contrib.auth.models import User, Permission, Group
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from user.models import Token


class UserSerializers(serializers.ModelSerializer):
    roles = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ['id', 'username', 'roles']

    def get_roles(self, obj):
        if obj.username:
            roles = User.objects.get(username=obj.username).user_permissions.values()
            roles_list = []
            for role in roles:
                roles_list.append(role['codename'])
            return roles_list
        return None


class TokenSerializers(serializers.ModelSerializer):
    class Meta:
        model = Token
        fields = '__all__'


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):

    def validate(self, attrs):
        data = super().validate(attrs)

        refresh = self.get_token(self.user)

        # data['refresh'] = str(refresh)
        accesstoken = {'accesstoken': str(refresh.access_token)}
        del data['access']
        del data['refresh']
        data['message'] = '请求成功'
        data['code'] = 20000
        data['username'] = self.user.username
        data['data'] = accesstoken
        data['systemTime'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        return data
